//
//  PublishEventTableViewController.m
//  StanfordEvents
//
//  Created by Gongmyung on 7/6/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "PublishEventTableViewController.h"
#import "StanfordEventsAppDelegate.h"


@implementation PublishEventTableViewController

@synthesize delegate;

#pragma mark -
#pragma mark View lifecycle

- (id)initWithStyle:(UITableViewStyle)style withContext:(NSManagedObjectContext*)context {
    managedObjectContext = context;
    [managedObjectContext retain];
    startDate = nil;
    endDate = nil;
    eventTitle = @"Title";
    eventHost = @"";
    eventDescription = @"Description";
    location = @"Location";
    
    NSError *error;
    NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
    [request setEntity:[NSEntityDescription entityForName:@"Tag" inManagedObjectContext:managedObjectContext]];
    tags = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    
    return [super initWithStyle:style];
}

- (void)viewDidLoad {
    [self setTitle:@"Create Event"];
    
    UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]
                                   initWithTitle:NSLocalizedString(@"Save", @"Save - for button to save changes")
                                   style:UIBarButtonItemStylePlain
                                   target:self
                                   action:@selector(save)];
    self.navigationItem.rightBarButtonItem = saveButton;
    [saveButton release];
    
    locationNotSet = YES;
    
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    //self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

-(IBAction)save
{
    Event *event = (Event *)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:managedObjectContext];
    StanfordEventsAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    NSString *username, *password, *pid;
    
    NSUserDefaults *defaultSettings = [NSUserDefaults standardUserDefaults];
    username = [defaultSettings stringForKey:@"username"];
    password = [defaultSettings stringForKey:@"password"];
    pid = [defaultSettings stringForKey:@"pid"];
    
    // [event setLatitude:[NSNumber numberWithDouble:coordinate.latitude]];
    // [event setLongitude:[NSNumber numberWithDouble:coordinate.longitude]];
    [event setTitle:eventTitle];
    [event setEventdescription:eventDescription];
    [event setEventtype:[NSNumber numberWithInt:0]];
    [event setHost:eventHost];
    [event setStarttime:startDate];
    [event setEndtime:endDate];
    [event setLocation:location];
    if( locationNotSet == YES ) {
        [event setLatitude:[NSNumber numberWithDouble:37.4241667]];
        [event setLongitude:[NSNumber numberWithDouble:-122.165]];
    }
    else {
        [event setLatitude:[NSNumber numberWithDouble:latitude]];
        [event setLongitude:[NSNumber numberWithDouble:longitude]];
    }
    [event setMine:[NSNumber numberWithInt:1]];
    [event setPid:[NSNumber numberWithInt:[pid intValue]]];
    if ( tagSet.count == 0) {
        NSError *error;
        NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
        [request setEntity:[NSEntityDescription entityForName:@"Tag" inManagedObjectContext:managedObjectContext]];
        [request setPredicate:[NSPredicate predicateWithFormat:@"name like 'Uncategorized'"]];
        // describe how we want the data sorted
        NSMutableArray *results = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
        if (results.count == 0) {
            Tag *tag = (Tag *)[NSEntityDescription insertNewObjectForEntityForName:@"Tag" inManagedObjectContext:managedObjectContext];
            
            tag.name = @"Uncategorized";
            
            [managedObjectContext save:&error];
            
            [appDelegate.filtersTableViewController addFilterToList:tag];
        }
        [event setTags:[NSSet setWithArray:results]];
    }
    else {
        [event setTags:tagSet];
    }
    
    /*
     *send event to server
     */
    NSLog(@"about to create json object");
    
    //create a json object with the event properties
    NSMutableDictionary *eventDict = [[NSMutableDictionary alloc] init];
    [eventDict setObject:[event title] forKey:@"title"];
    [eventDict setObject:[event eventdescription] forKey:@"description"];
    [eventDict setObject:[event eventtype] forKey:@"eventtype"];
    [eventDict setObject:[event host] forKey:@"host"];
    [eventDict setObject:[NSNumber numberWithDouble:[[event starttime] timeIntervalSince1970]] forKey:@"starttime"];
    [eventDict setObject:[NSNumber numberWithDouble:[[event endtime] timeIntervalSince1970]] forKey:@"endtime"];
    [eventDict setObject:[event location] forKey:@"location"];
    [eventDict setObject:[event latitude] forKey:@"latitude"];
    [eventDict setObject:[event longitude] forKey:@"longitude"];
    NSLog(@"about to parse json object");
    
    //parse object into json
    SBJSON *parser = [[SBJSON alloc] init];
    NSString *jsonEvent = [parser stringWithObject:eventDict];
    
    NSLog(@"parsed json object");
    
    NSURL *url = [NSURL URLWithString:@"http://colby.stanford.edu/community_vibe/concierge/rpc.php"];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    
    [request setPostValue:username forKey:@"name"];
    [request setPostValue:password forKey:@"key"];
    [request setPostValue:@"postMessage" forKey:@"do"];
    [request setPostValue:jsonEvent forKey:@"content"];
    
    NSString *tagsString = @"stanford_events,create,";
    NSMutableArray *tagsToSend = [[NSMutableArray alloc] init];
    for( Tag* t in tagSet ) {
        [tagsToSend addObject:t.name];
        NSLog(@"tag added");
    }
    NSString *tagsToAppend = [tagsToSend componentsJoinedByString:@","];
    if (tagsToAppend != nil && tagsToAppend.length > 0) {
        tagsString = [tagsString stringByAppendingString:tagsToAppend];
    }
    [request setPostValue:tagsString forKey:@"tags"];    
    [request startSynchronous];
    NSError *error = [request error];
    NSString *response;
    if (!error) {
        response = [request responseString];
    }
    int eventID = [response intValue];
    [event setEid:[NSNumber numberWithInt:eventID]];
    
    error;
    if (![managedObjectContext save:&error]) {
        NSLog(@"failed to save created event");
    }
    
    //TODO: put up pinwheel and poll aldksfjaldks./pid=x until we get a response
    
    //add event to my events table
    [self.delegate PublishEventViewControllerDidFinish:event];
    //add event to map controller
    [appDelegate.mapViewController addEvent:event];
    
    //check if event is nearby, if it is add to localevents controller
    double x = (appDelegate.eventsListViewController.locationManager.location.coordinate.latitude-[event.latitude doubleValue])*69.1;
    double y = (appDelegate.eventsListViewController.locationManager.location.coordinate.longitude-[event.longitude doubleValue])*69.1;
    double dist = sqrt( x*x+y*y );
    if ( dist < 0.8 ) {
        [appDelegate.localEventsListViewController addEvent:event];
    }
    
    [tagsToSend release];
    [eventDict release];
    [[self.delegate navController] popViewControllerAnimated:YES];
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 4;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  
{  
    switch (indexPath.section) {
        case 0:
            return 88;
            break;
        case 1:
            return 66;
            break;
        default:
            return 44;
            break;
    }
     return 80.0; //returns floating point which will be used for a cell row height at specified row index  
}  

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    static NSString *DescriptionCellIdentifier = @"descriptionCell";
    static NSString *DateCellIdentifier = @"dateCell";
    UITableViewCell *cell;
    EventDescriptionTableCell *descCell;
    EventDateTableCell *dateCell;
    
    // Configure the cell...
    switch (indexPath.section) {
        case 0:
            descCell = (EventDescriptionTableCell*)[tableView dequeueReusableCellWithIdentifier:DescriptionCellIdentifier];
            if (descCell == nil) {
                NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"EventDescriptionTableCell" owner:nil options:nil];
                
                for(id currentObject in nibObjects ) {
                    if([currentObject isKindOfClass:[EventDescriptionTableCell class]]) {
                        descCell = (EventDescriptionTableCell*)currentObject;
                        break;
                    }
                }
            }
            descCell.eventTitle.text = eventTitle;
            descCell.eventDescription.text = eventDescription;
            descCell.eventHost.text = [NSString stringWithFormat:@"Hosted by: %@", eventHost];
            cell = descCell;
            break;
        case 1:
            dateCell = (EventDateTableCell*)[tableView dequeueReusableCellWithIdentifier:DateCellIdentifier];
            if (dateCell == nil) {
                NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"EventDateTableCell" owner:nil options:nil];
                
                for(id currentObject in nibObjects ) {
                    if([currentObject isKindOfClass:[EventDateTableCell class]])
                        dateCell = (EventDateTableCell*)currentObject;
                }
            }
            if( startDate == nil || endDate == nil ) {
                dateCell.startDate.text = @"";
                dateCell.endDate.text = @"";
            }
            else {
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
                [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
                dateCell.startDate.text = [dateFormatter stringFromDate:startDate];
                dateCell.endDate.text = [dateFormatter stringFromDate:endDate];
            }
            cell = dateCell;
            break;
        case 2:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            }
            [cell.textLabel setText:location];
            break;
        default:
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            }
            [cell.textLabel setText:@"Tags"];
            break;
    }
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"Hello");
    
    if( indexPath.section == 0 ) {
        DetailWriterViewController *detailWriter = [[DetailWriterViewController alloc] initWithNibName:@"DetailWriterViewController" bundle:nil];
        detailWriter.delegate = self;
        [self.navigationController pushViewController:detailWriter animated:YES];
        [detailWriter release];
    }
    else if( indexPath.section == 1 ) {
        DatePickerViewController *datePicker = [[DatePickerViewController alloc] init];
        datePicker.delegate = self;
        [self.navigationController pushViewController:datePicker animated:YES];
        [datePicker release];
    }
    else if( indexPath.section == 2 ) {
        LocationPickerViewController *locationPicker = [[LocationPickerViewController alloc] initWithNibName:@"LocationPickerViewController" bundle:nil];
        locationPicker.delegate = self;
        [self.navigationController pushViewController:locationPicker animated:YES];
        [locationPicker release];
    }
    else {
        TagsPickerTableViewController *tagsPickerController = [[TagsPickerTableViewController alloc] initWithStyle:UITableViewStylePlain andTags:tags andContext:managedObjectContext]; 
        tagsPickerController.delegate = self;
        [self.navigationController pushViewController:tagsPickerController animated:YES];
        [tagsPickerController release];
    }

}


/*
 * Delegate methods for the various pickers
 */

- (void)setLocation:(NSString*)loc withLatitude:(double)lat withLogitude:(double)lon {
    location = loc;
    [location retain];
    latitude = lat;
    longitude = lon;
    locationNotSet = NO;
    [self.tableView reloadData];
}
- (void)setTitle:(NSString *)tit andHost:(NSString*)host andDescription:(NSString*)desc {
    eventTitle = [NSString stringWithString:tit];
    [eventTitle retain];
    eventDescription = [NSString stringWithString:desc];
    [eventDescription retain];
    eventHost = [NSString stringWithString:host];
    [eventHost retain];
    [self.tableView reloadData];
}
- (void)setStartDate:(double)start endDate:(double)end {
    startDate = [NSDate dateWithTimeIntervalSince1970:start];
    [startDate retain];
    endDate = [NSDate dateWithTimeIntervalSince1970:end];
    [endDate retain];
    [self.tableView reloadData];
}
- (void)setTags:(NSMutableArray*)tags_ tagSet:(NSMutableSet*)tagSet_{
    tags = tags_;
    [tags retain];
    tagSet = tagSet_;
    [tagSet retain];
    //NSLog(@"Tagset size: %i", tagSet.count);
}

- (UINavigationController *)navController {
    return self.navigationController;
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [managedObjectContext release];
    [tags release];
    [tagSet release];
    [startDate release];
    [endDate release];
    [location release];
    [eventTitle release];
    [eventDescription release];
    [eventHost release];
    [super dealloc];
}


@end

